import { query,queryPress,queryFlowmeter } from '@/services/meters';
import moment from 'moment';
import {todayLastSecond} from '@/utils/utils.js'
import createRowData from '@/utils/createRowData';
import TileLayer from 'ol/layer/Tile';
import XYZ from 'ol/source/XYZ';
import find from 'lodash/find'
//星图地球地图
import { get as getProjection } from 'ol/proj'
import { getTopLeft, getWidth } from 'ol/extent'
import TileGrid from 'ol/tilegrid/TileGrid'
const projection = getProjection('EPSG:3857')
const matrixIds = []
const tileSizePixels = 256
const tileSizeMtrs = getWidth(projection.getExtent()) / tileSizePixels
const resolutions = []
for (let i = 0; i <= 18; i++) {
  matrixIds[i] = i
  resolutions[i] = tileSizeMtrs / Math.pow(2, i)
}
const tileGrid = new TileGrid({
  origin: getTopLeft(projection.getExtent()),
  resolutions: resolutions,
  matrixIds: matrixIds,
})

export default {
  namespace: 'meters_map',
  state: {
    pageLoaded:false,
    tableY:300,
    OriginData:[],
    data:[],
    pressData:[],
    pointData: {},
    flowmeterData:[],
    scrollData:{x:0,y:0},
    selectedRowKeys: [0],
    show_type:'',
    waterVisiable: true,
    pressVisiable: true,
    flowmeterVisiable: true,
    searchParams:{
      name:'',
      number:'',
      imei:'',
      address:'',
      online_status:'',
      alarm:'',
    },
    meta: {total: 0, per_page: 50,current_page:1},
    additional: {total_count: 0, online_count: 0},
    loading: true,
    editRecord:{},
    detail:{
      pageLoaded:false,
      isDetail:false,
    },
    zoom: 16,
    center:[118.2531003320584, 25.494425539585507],
    layers: [
      new TileLayer({
        title: '天地图卫星影像',
        visible: true,
        source: new XYZ({
          // url: 'http://t3.tianditu.com/DataServer?T=img_w&x={x}&y={y}&l={z}&tk=b45faf8590f42059eb14fc6065fc9606',
          url: 'https://tiles1.geovisearth.com/base/v1/img/{z}/{x}/{y}?format=webp&tmsIds=w&token=6dd3767b369eb5b724937e4ad74b2e78e95ad67ac7bbc1049539cb0691ad6ca2',//星图地球
          tileGrid: tileGrid, // 星图地球指定切片的网格参数
        }),
      }),
      new TileLayer({
        title: '天地图矢量图',
        visible: false,
        source: new XYZ({
          url: 'http://t3.tianditu.com/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=b45faf8590f42059eb14fc6065fc9606',
          tileGrid: tileGrid, // 星图地球指定切片的网格参数
        }),
      }),
      new TileLayer({
        title: '卫星标注',
        visible: true,
        source: new XYZ({
          // url: 'http://t4.tianditu.com/DataServer?T=cia_w&x={x}&y={y}&l={z}&tk=b45faf8590f42059eb14fc6065fc9606',
          url: 'https://tiles1.geovisearth.com/base/v1/cia/{z}/{x}/{y}?format=png&tmsIds=w&token=6dd3767b369eb5b724937e4ad74b2e78e95ad67ac7bbc1049539cb0691ad6ca2',//星图地球
          tileGrid: tileGrid, // 星图地球指定切片的网格参数
        }),
      }),
      new TileLayer({
        title: '矢量图标注',
        visible: false,
        source: new XYZ({
          url: 'http://t4.tianditu.com/DataServer?T=cva_w&x={x}&y={y}&l={z}&tk=b45faf8590f42059eb14fc6065fc9606',
          tileGrid: tileGrid, // 星图地球指定切片的网格参数
        }),
      }),

    ],
  },
  effects: {
    *changeIsDetail({ payload, callback }, { call, put ,select}) {
      console.log('changeIsDetail')
      const {detail} = yield select(state => state.meters)
      yield put({
        type: 'changeDetail',
        payload:{
          ...detail,
          isDetail:!detail.isDetail,
          detailId:payload.id,
        }
      });
    },
    * fetchPointData({ payload, callback }, { call, put, select }) {
      console.log('fetchPointData');
      const state = yield select(state => state.meters_map);//获取state中的数据
      const response = find(state.pressData, (o) => {
        return o.id === payload.id;
      });
      console.log('response',response)
      if (response) {
        yield put({
          type: 'savePointData',
          payload: { ...response },
        });
        if (callback) callback();
      }
    },
    *reset({ payload, callback }, { call, put }) {
      console.log('reset=============')
      yield put({
        type: 'resetData',
        payload:payload
      });
      if(callback) callback()
    },
    *changeTableY({ payload, callback }, { call, put }) {
      const tableY=document.body.offsetHeight -
        document.querySelector('.search-form').getBoundingClientRect().top -55;
      yield put({
        type: 'saveTableY',
        payload: tableY
      });
      if(callback)callback()
    },
    *changeSearchParams({ payload, callback }, { call, put }) {
      console.log('changeSearchParams')
      yield put({
        type: 'saveSearchParams',
        payload: payload
      });
    },
    *changeLoaded({ payload, callback }, { call, put }) {
      yield put({
        type: 'changePageLoaded',
        payload: true,
      });
    },
    *changeScroll({ payload, callback }, { call, put }) {
      yield put({
        type: 'changeScrollData',
        payload: payload,
      });
    },
    *selectRow({payload, callback}, {call, put,select}) {
      const {selectedRowKeys} = yield select(state => state.meters_map)
      if (selectedRowKeys.indexOf(payload.id) >= 0) {
        selectedRowKeys.splice(selectedRowKeys.indexOf(payload.id), 1);
      } else {
        selectedRowKeys.push(payload.id);
      }
      yield put({
        type: 'saveSelectRow',
        payload: selectedRowKeys,
      });
    },
    *changeOneState({ payload, callback }, { call, put }) {
      console.log('changeOneState',payload)
      yield put({
        type: 'saveState',
        payload: payload,
      });
      setTimeout(function() {
        if (callback) callback();
      },0)

    },
    *fetch({ payload,callback }, { call, put ,select}) {
      yield put({
        type: 'changeLoading',
        payload: true,
      });
      const state = yield select(state => state.meters_map)//获取state中的数据
      payload=payload||state.searchParams;
      console.log('payload',payload)
      // const response = yield call(query, {...payload,per_page:'500'});
      const pressResponse = yield call(queryPress, {...payload,per_page:'500'});
      const pressResponse2 = yield call(queryPress, {per_page:'500'});
      // const flowmeterResponse = yield call(queryFlowmeter, {...payload,per_page:'500'});
      // console.log(response)
      if(pressResponse.data.status_code===200){
        // yield put({
        //   type: 'save',
        //   payload:  response.data
        // });
        yield put({
          type: 'savePress',
          payload:  pressResponse.data
        });
        yield put({
          type: 'savePress2',
          payload:  pressResponse2.data
        });
        // yield put({
        //   type: 'saveFlowmeter',
        //   payload:  flowmeterResponse.data
        // });
        yield put({
          type: 'saveSearchParams',
          payload: payload
        });
        yield put({
          type: 'changeLoading',
          payload: false,
        });
        if (callback) callback();
      }


    },
  },

  reducers: {
    savePointData(state, action) {
      return {
        ...state,
        pointData: { ...action.payload, my_time: moment().format('YYYY-MM-DD HH:mm:ss') },
      };
    },
    saveState(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    },
    save(state, action) {
      return {
        ...state,
        data: action.payload.data,
      };
    },
    savePress(state, action) {
      return {
        ...state,
        pressData: action.payload.data,
      };
    },
    savePress2(state, action) {
      return {
        ...state,
        OriginData: action.payload.data,
      };
    },
    saveFlowmeter(state, action) {
      return {
        ...state,
        flowmeterData: action.payload.data,
      };
    },
    saveTableY(state, action) {
      return {
        ...state,
        tableY: action.payload,
      };
    },
    saveOneRecord(state, action) {
      return {
        ...state,
        editRecord:action.payload
      };
    },
    changeLoading(state, action) {
      return {
        ...state,
        loading: action.payload,
      };
    },
    changePageLoaded(state, action) {
      return {
        ...state,
        pageLoaded: action.payload,
      };
    },
    changeScrollData(state, action) {
      return {
        ...state,
        scrollData: action.payload,
      };
    },
    saveSearchParams(state, action) {
      return {
        ...state,
        searchParams: {
          ...state.searchParams,
          ...action.payload
        },
      };
    },
    resetData(state, action) {
      return  {
        pageLoaded:action.payload,
        tableY:state.tableY,
        data:[],
        pressData:[],
        pointData: {},
        scrollData:{x:0,y:0},
        selectedRowKeys: [],
        flowmeterData:[],
        show_type:'',
        pressVisiable: true,
        waterVisiable: true,
        flowmeterVisiable: true,
        searchParams:{
          name:'',
          number:'',
          imei:'',
          address:'',
          online_status:'',
          alarm:'',
        },
        meta: {total: 0, per_page: 0,current_page:1},
        loading: true,
        editRecord:{},
        additional: {total_count: 0, online_count: 0},
        detail:{
          pageLoaded:false,
          isDetail:false,
        },
        zoom: 16.3,
        center:[113.10010585408295, 27.823123599885434],
        layers: [
          new TileLayer({
            title: '天地图卫星影像',
            visible: true,
            source: new XYZ({
              url: 'http://t3.tianditu.com/DataServer?T=img_w&x={x}&y={y}&l={z}&tk=b45faf8590f42059eb14fc6065fc9606',
            }),
          }),
          new TileLayer({
            title: '天地图矢量图',
            visible: false,
            source: new XYZ({
              url: 'http://t3.tianditu.com/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=b45faf8590f42059eb14fc6065fc9606',
            }),
          }),
          new TileLayer({
            title: '卫星标注',
            visible: true,
            source: new XYZ({
              url: 'http://t4.tianditu.com/DataServer?T=cia_w&x={x}&y={y}&l={z}&tk=b45faf8590f42059eb14fc6065fc9606',
            }),
          }),
          new TileLayer({
            title: '矢量图标注',
            visible: false,
            source: new XYZ({
              url: 'http://t4.tianditu.com/DataServer?T=cva_w&x={x}&y={y}&l={z}&tk=b45faf8590f42059eb14fc6065fc9606',
            }),
          }),

        ],
      };
    },
    saveSelectRow(state, action) {
      return {
        ...state,
        selectedRowKeys: action.payload,
      };
    },
  },

};
